<?php

namespace IDock\Insurance\HBIC\Request;

use Exception;
use IDock\Insurance\HBIC\HBICEnums;
use IDock\Insurance\HBIC\Response\CancelOrderResponse;
use IDock\Insurance\HBIC\Response\CommonResponse;
use IDock\Insurance\HBIC\Response\InsuranceOrderQueryResponse;
use IDock\Insurance\HBIC\Response\NonCarOrderInquiryResponse;
use IDock\Printer\NonCar\NonCarSubCoveragePrinter;
use IDock\Visitor\NonCar\NonCarProductVisitor;
use IDock\Visitor\Premium\PremiumInquiryVisitor;
use IDock\Visitor\UnderwritingRecallVisitor;
use IDock\Visitor\UploadFileVisitor;

/**
 * 非车投保
 */
class NonCarOrderInquiryRequest extends AllHBICRequest
{
    public $requestType = 'BXT';

    protected $response = NonCarOrderInquiryResponse::class;

    protected $urlTip = '非车投保';

    public $isNonCar = true;

    /**
     * @var PremiumInquiryVisitor $visitor
     */
    protected $visitor;


    public function generate(): array
    {
        return [
            'BASEINFO' => $this->getBaseInfo(),
            'APPNT' => $this->getApplicant(),
            'RISK' => $this->getRisk(),
            'ITEM_KIND_LIST' => ['ITEM_KIND' => $this->getCoverageList()],
            'RISK_DYNAMIC' => $this->getRiskDynamic(),
            'ITEMACCI_' => $this->getVehicle(),
            'RISK_SPECIAL_CLAUSES_DTO' => $this->getSpecialClause()
        ];
    }

    protected function getBaseInfo()
    {
        /**@var NonCarProductVisitor $single */
        $single = $this->visitor->getNonCarUnderwritingVisitor()->getNonCarList()[0] ?? [];
        $arr = [
            'AMT' => round($single->argc['noCarAmount'] ?? '0', 2),
            'PREMIUM' => round($single->premium * $single->insuredNum, 2),
            'BUSINESSCHANNEL' => $this->visitor->getExtInfoVisitor()->argc['CHANNELDETAILCODE'] ?? '',//渠道细类
            'CHANNELDETAILCODE' => $this->visitor->getExtInfoVisitor()->argc['CHANNELTIP'] ?? '',//渠道小类
            'COMPANYCODE' => $this->visitor->getExtInfoVisitor()->argc['COMPANYCODE'] ?? '0106010101',//业务归属机构代码
            'CREATETIME' => date('Y-m-d H:i:s'),
            'INSRNTCNAME' => $this->visitor->getInsuredVisitor()->name,
            'SOLUTIONCODE' => $this->visitor->getExtInfoVisitor()->argc['SUBAGRTNO'] ?? '',//子协议代码
            'SALESMANCODE' => $this->visitor->getExtInfoVisitor()->argc['SALESMANCODE'] ?? '',//归属业务员代码
            'AGREEMENTCODE' => $this->visitor->getExtInfoVisitor()->argc['AGREEMENTNO'] ?? '',//协议代码
            'INSUREDADDR' => $this->visitor->getInsuredVisitor()->address,
            'BUSINESSMODE' => '2',//业务方式
            'RISKCODE' => '1119',
            'BUYNUM' => $single->insuredNum,
            'NUCLEARTYPE' => 'Y',//是否需要提核N
        ];
        if(empty($arr['AMT'])){
            throw new Exception("非车总保费不能为空");
        }
        return $arr;
    }

    protected function getApplicant()
    {
        $arr = [
            'INSUREDTYPE' => $this->visitor->getApplicantVisitor()->typeCode == 'R1' ? '1' : '2',
            'INSUREDMOBILEPHONE' => $this->visitor->getApplicantVisitor()->mobile,
            'INSUREDEMAIL' => $this->visitor->getApplicantVisitor()->email,
            'INSUREDCOMPANY' => '',
            'INSUREDZIP' => $this->visitor->getApplicantVisitor()->postcode,
            'INSUREDCERTTYPE' => HBICEnums::$certificateTypeCode[$this->visitor->getApplicantVisitor()->certificateTypeCode] ?? '',
            'INSUREDADDR' => $this->visitor->getApplicantVisitor()->address,
            'INSUREDCERTNO' => $this->visitor->getApplicantVisitor()->certificateNo,
            'INSUREDCNAME' => $this->visitor->getApplicantVisitor()->name,
            'INSUREDPHONE' => $this->visitor->getApplicantVisitor()->mobile,
            'CONTACTNAME' => '',
            'CONTACTIDENTIFYTYPE' => '',
            'CONTACTSEX' => '',
            'CONTACTIDENTIFYNUMBER' => '',
            'CONTACTMOBILE' => '',
            'CONTACTTYPE' => '',
        ];
        if ($arr['INSUREDTYPE'] != '1') {
            throw new \Exception("驾意险不支持该用户类型");
        }
        $arr['INSUREDBIRTHDAY'] = substr($this->visitor->getApplicantVisitor()->certificateNo, 6, 8);
        $arr['INSUREDSEX'] = $this->getGenderByIDcard($this->visitor->getApplicantVisitor()->certificateNo);
        return $arr;
    }

    protected function getRisk()
    {
        return [
            'BEGINTIME' => $this->visitor->biStartData,
            'ENDTIME' => $this->visitor->biEndData,
            'PLANCODE' => '1119',
//            'PERIOD' => '366',
        ];
    }

    public function getCoverageList()
    {
        $list = [];
        /**@var NonCarProductVisitor $single */
        $single = $this->visitor->getNonCarUnderwritingVisitor()->getNonCarList()[0] ?? [];
        $seat = $this->visitor->getVehicleVisitor()->vehicleSeat;
        if(empty($seat)){
            throw new Exception("车辆座位数不能为空");
        }
        /**
         * @var NonCarSubCoveragePrinter $val
         */
        foreach ($single->subCoverage as $val){
            $item = [
                'INSRNTCNAME' => $val->subName,//名称
                'LIABAMT' => round($val->amount * $seat,2),//总保险金额
                'KINDCODE' => $val->subCode,//险别代码
                'BEGINTIME' => $this->visitor->biStartData,//起保日期
                'LIABPRM' => $seat ? round($val->premium / $seat,2) : 0,//基础保费
                'LIABRATE' => $val->rate,//费率
                'GROSSPREMIUM' => round($val->premium,2),//总保费
                'UNITINSURED' =>   round($val->amount ,2),//单位保额
                'UNITPREMIUM' => $seat? round($val->premium / $seat,2) : 0,//单位保费
                'QUANTITY_EXT' => $seat,//人数
            ];
            $list[] = $item;
            unset($item);
        }
        return $list;
    }

    protected function getRiskDynamic()
    {
        return [
            'VFACTOR3' => $this->visitor->getVehicleVisitor()->vin,
            'VFACTOR2' => $this->visitor->getVehicleVisitor()->engineNo,
            'VFACTOR4' => $this->visitor->getVehicleVisitor()->vehicleSeat,
            'VFACTOR1' => $this->visitor->getVehicleVisitor()->licenseNo,
            'FILDAA' => '',
            'FIELDAE' => $this->visitor->getApplicantVisitor()->typeCode == 'R1' ? '家庭自用' : '企业自用',
            'FIELDAI' => HBICEnums::$useNatureCode[$this->visitor->getVehicleVisitor()->useNatureCode] ?? '',
            'FieldAJ' => HBICEnums::$carKindCode[$this->visitor->getVehicleVisitor()->carKindCode] ?? '',
            'FieldAK' => $this->visitor->getVehicleVisitor()->vehicleTonnage ,
        ];
    }

    protected function getVehicle()
    {
        /**@var NonCarProductVisitor $single */
        $single = $this->visitor->getNonCarUnderwritingVisitor()->getNonCarList()[0] ?? [];
        return [
            'OCCUPATIONTYPE' => '',
            'OCCUPATIONTYPENAME' => '企业职员',
            'OCCUPATIONCODE' => '60',
            'OCCUPA' => '',
            'OCCUPALEVEL' => '',
            'QUANTITY' => $this->visitor->getVehicleVisitor()->vehicleSeat,
            'BUYNUM' => $single->insuredNum,
            'RISKCODE' => '1119',
            'RISKPLANCODE' => '',
        ];
    }

    protected function getSpecialClause()
    {
        /**@var NonCarProductVisitor $single */
        $single = $this->visitor->getNonCarUnderwritingVisitor()->getNonCarList()[0] ?? [];
        $clauseList = $single->argc['specialClause'] ?? [];
        $list = [];
        foreach ($clauseList as $value){
            $list[] = [
                'REMARK' => $value['content'] ?? '',
                'clauseCode' => $value['code'] ?? '',
                'clauseCName' => $value['name'] ?? '',
            ];
        }
        return $list;
    }

    private function getGenderByIDcard($idCard)
    {
        if (strlen($idCard) != 18) {
            throw new Exception("身份证位数不合法");
        }
        $gender = intval(substr($idCard, 16, 1)) % 2;
        return $gender ? '1' : '2';
    }

}
